package dsx.slicer;

import java.util.Arrays;

import dsx.cache.DsxByteBuffer;
import dsx.inf.ISlicer;

public class Slicer_space implements ISlicer {

	@Override
	public byte[] slice(DsxByteBuffer buf) {
		try {
			byte[] pack = null;
			int packLen = 0;
			byte curByte = 0;
			byte[] tempBytes = new byte[buf.readableLen()];
			while (buf.readable()) {
				curByte = buf.get();
				if (curByte == 0 && packLen > 0) {
					pack = Arrays.copyOfRange(tempBytes, 0, packLen);
					buf.discard();
					return pack;
				} else {
					tempBytes[packLen] = curByte;
					packLen++;
				}
			}
			buf.reset();
		} catch (Exception ex) {
			buf.clear();
		}
		return null;
	}

	@Override
	public byte[] pack(byte[] data) {
		byte[] buf = new byte[data.length + 1];
		System.arraycopy(data, 0, buf, 0, data.length);
		buf[buf.length - 1] = 0;
		return buf;
	}


}
